package com.itcam.daijia.rules.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itcam.daijia.common.result.Result;
import com.itcam.daijia.model.entity.rule.FeeRule;
import com.itcam.daijia.model.form.rules.FeeRuleRequest;
import com.itcam.daijia.model.form.rules.FeeRuleRequestForm;
import com.itcam.daijia.model.vo.rules.FeeRuleResponse;
import com.itcam.daijia.model.vo.rules.FeeRuleResponseVo;
import com.itcam.daijia.rules.mapper.FeeRuleMapper;
import com.itcam.daijia.rules.service.FeeRuleService;
import com.itcam.daijia.rules.utils.DroolsHelper;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.Date;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class FeeRuleServiceImpl implements FeeRuleService {

    @Autowired
    private KieContainer kieContainer;

    @Autowired
    private FeeRuleMapper feeRuleMapper;


    /**
     * 计算订单费用
     * @param feeRuleRequestForm 包含计算费用所需信息的请求表单
     * @return 计算后的订单费用响应
     */
    @Override
    public FeeRuleResponseVo calculateOrderFee(FeeRuleRequestForm feeRuleRequestForm) {
        // 1. 封装传入对象
        FeeRuleRequest feeRuleRequest = new FeeRuleRequest();
        feeRuleRequest.setDistance(feeRuleRequestForm.getDistance());
        feeRuleRequest.setStartTime(new DateTime(feeRuleRequestForm.getStartTime()).toString("HH:mm:ss"));
        feeRuleRequest.setWaitMinute(feeRuleRequestForm.getWaitMinute());
        log.info("传入参数：{}", JSON.toJSONString(feeRuleRequest));

        //获取最新订单费用规则
        FeeRule feeRule = feeRuleMapper.selectOne(new LambdaQueryWrapper<FeeRule>().orderByDesc(FeeRule::getId).last("LIMIT 1"));
        KieSession kieSession = DroolsHelper.loadForRule(feeRule.getRule());

        // 2. 开启规则引擎会话
//        KieSession kieSession = kieContainer.newKieSession();

        // 3. 封装返回对象
        FeeRuleResponse feeRuleResponse = new FeeRuleResponse();
        kieSession.setGlobal("feeRuleResponse", feeRuleResponse);

        // 4. 将订单对象插入规则引擎
        kieSession.insert(feeRuleRequest);

        // 5. 触发规则引擎中的所有规则
        kieSession.fireAllRules();

        // 6. 中止会话，释放资源
        kieSession.dispose();

        log.info("计算结果：{}", JSONArray.toJSONString(feeRuleRequest));

        // 7. 封装返回对象
        FeeRuleResponseVo feeRuleResponseVo = new FeeRuleResponseVo();
        BeanUtils.copyProperties(feeRuleResponse, feeRuleResponseVo);

        return feeRuleResponseVo;
    }


}
